/*
 * Avatar crop
 */

$(document).ready(function(){
});

var ratio = 80/80;
var jcrop_api;


function onClickMakeAvatar(area)
{
	cropboxLoad(area, 'id_see_img');
	$('#id_see_avatar_make'+area).hide();
	$('#id_see_avatar_save'+area).show();
	$('#id_see_avatar_cancel'+area).show();
	return false;
}

function onClickSaveAvatar(area)
{
	if ( checkCoords(area) )
		$('#id_saveAvatar_submit'+area).click();
    $('#sd_closelabel img').click();
	return false;
}

function onClickCancelAvatar(area)
{
	if (typeof jcrop_api != 'undefined'){
		destroyCrop(area);
	}
	$('#id_see_avatar_make'+area).show();
	$('#id_see_avatar_save'+area).hide();
	$('#id_see_avatar_cancel'+area).hide();
	return false;
}


function initJcrop(area, idBox) {
	jcrop_api = $.Jcrop('#'+idBox+area);
	jcrop_api.setOptions({
		aspectRatio: ratio,
		minSize: [80,80],
		onSelect: function (c) {updateCoords(area, c)}
	});
}

function nothing(e) {
	e.stopPropagation();
	e.preventDefault();
	return false;
}

function cropboxLoad(area, idBox) {
	initJcrop(area, idBox);
	setSelection(area);
	return false;
	//return nothing(e);
}

function setSelection(area) {
	var dim = jcrop_api.getBounds();
	if (dim[0]/dim[1] > ratio) {
		var xc = dim[0]/2,
			w2 = dim[1]*ratio/2;
		jcrop_api.setSelect([Math.round(xc-w2), 0, Math.round(xc+w2), dim[1]]);
		jQuery('#id_saveAvatar_x'+area).val(Math.round(xc-w2));
		jQuery('#id_saveAvatar_y'+area).val(0);
		jQuery('#id_saveAvatar_w'+area).val(Math.round(xc+w2));
		jQuery('#id_saveAvatar_h'+area).val(dim[1]);
	} else {
		var yc = dim[1]/2,
			h2 = dim[0]/(ratio*2);
		jcrop_api.setSelect([0, Math.round(yc-h2), dim[0], Math.round(yc+h2)]);
		jQuery('#id_saveAvatar_x'+area).val(0);
		jQuery('#id_saveAvatar_y'+area).val(Math.round(yc-h2));
		jQuery('#id_saveAvatar_w'+area).val(dim[0]);
		jQuery('#id_saveAvatar_h'+area).val(Math.round(yc+h2));
	}
}

function updateCoords(area,c) {
	jQuery('#id_saveAvatar_x'+area).val(c.x);
	jQuery('#id_saveAvatar_y'+area).val(c.y);
	jQuery('#id_saveAvatar_w'+area).val(c.w);
	jQuery('#id_saveAvatar_h'+area).val(c.h);
}

function checkCoords(area) {
	if (parseInt(jQuery('#id_saveAvatar_w'+area).val())>0) return true;
	alert(Dictionary.translate('lang_photostudio_crop_select_region'));
	//alert('Please select a crop region then press submit.');
	return false;
}

function destroyCrop(area) {
	jcrop_api.destroy();
	return false;
	//return nothing(e);
}

//$(window).load(cropboxLoad());
